<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Role;
use App\Http\Resources\UserResource;
use App\Http\Requests\RoleRequest;


class RoleController extends Controller
{

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function home(Request $request)
    {
		$data['code']=0;
		$data['data']=Role::paginate(12);
		$data['error']="";
		$data['msg']="success";
		$data['timestamp']=time();
		return $data;
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(RoleRequest $request)
    {
		$data=[
			'name' => $request->name,
			'status' => $request->status,
			'desc' => $request->desc				
		];
		
	   if($role=Role::where("id",$request->id)->first()){		   
		   $role->name=$request->name;
		   $role->status=$request->status;
		   $role->desc=$request->desc;
		   $role->save();
		   $role->access()->sync($request->access);
		   return ['code'=>0,"data"=>[],'msg'=>'修改成功'];
	   }
	   
	   if(!$request->id&&!Role::where("name",$request->name)->first()){
			Role::create($data);			
			return ['code'=>0,"data"=>[],'msg'=>'创建成功'];
	   }
	   return ['code'=>101,"data"=>[],'msg'=>'角色已存在'];
    }

    public function show(Request $request,$id)
    {
		$role=Role::where("id",$request->id)->where("is_system",'<>',1)->first();
		
		if($role){
		  $role->access;
          return ['code'=>0,"data"=>$role,'msg'=>'获取成功'];
		}else{
          return ['code'=>0,"data"=>[],'msg'=>'失败'];
		}       
	}
	
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function delete(Request $request)
    {
		if(Role::where("id",$request->id)->where("is_system",'<>',1)->delete()){
          return ['code'=>0,"data"=>1,'msg'=>'删除成功'];
		}else{
          return ['code'=>0,"data"=>0,'msg'=>'删除失败,你没有权限删除此角色'];
		}
    }
}
